import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;

public class Multicast extends Thread {
	
	MulticastSocket socket;
	InetAddress groupaddress;
	TokenPassing tp;
	public Multicast(TokenPassing tp) throws IOException {
		socket = new MulticastSocket(SystemConfig.getGroupPort());
		groupaddress = InetAddress.getByName(SystemConfig.getGroupAddr());
		socket.joinGroup(groupaddress);
		
		System.out.println("joined multicast group "+groupaddress+socket.getLocalPort());
		
		Utils.writeLog("joined multicast group "+groupaddress+socket.getLocalPort());
		this.tp=tp;
		this.setName("Multicast");
	}

	private void handlePacket(DatagramPacket packet) {
		String received = new String(packet.getData(), 0, packet.getLength());
			// create a packet and send
			InetAddress peeraddress = packet.getAddress();
			int peerport = packet.getPort();
			//TODO send the predecessor
			String data=new String();
			data+=SystemConfig.getPid();
			data+=" ";
			data+=tp.getPredecessor().getAddr();
			data+=" ";
			data+=tp.getPredecessor().getPort();
			data+=" ";
			data+=tp.getPredecessor().getPid();
				
			try {
				byte buf[]=data.getBytes("US-ASCII");
				DatagramPacket psend=new DatagramPacket(buf,buf.length,packet.getAddress(),packet.getPort());
				tp.sendPacket(psend);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} 
	}


	@Override
	public void run() {
		// TODO Auto-generated method stub
		DatagramPacket packet;
		while (true) {
			try {
				byte[] buf = new byte[256];
				packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				System.out.println("multicast packet received");
				Utils.writeLog("multicast packet recived "+packet.getPort()+packet.getAddress().getHostAddress());
				handlePacket(packet);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
